import router from '@system.router'
import prompt from '@system.prompt'
import storage from '@system.storage'
import voice from '@system.voice'
import device from '@system.device'
import sensor from '@system.sensor'

export default {
  data: {
    settings: {
      voiceRecognition: true,
      sceneAwareness: true,
      multiDeviceSync: false,
      soundEffects: true,
      backgroundMusic: true,
      musicVolume: 50,
      effectVolume: 70,
      language: 'zh-CN',
      theme: 'dark',
      fontSize: 'medium',
      difficulty: 'adaptive',
      autoSave: true,
      saveInterval: 300,
      notifications: true,
      vibration: true
    },
    deviceInfo: null,
    availableThemes: ['dark', 'light', 'auto'],
    availableLanguages: [
      { code: 'zh-CN', name: '简体中文' },
      { code: 'en-US', name: 'English' },
      { code: 'ja-JP', name: '日本語' }
    ],
    availableFontSizes: ['small', 'medium', 'large'],
    availableDifficulties: ['easy', 'medium', 'hard', 'adaptive'],
    isTestingVoice: false,
    voiceTestResult: '',
    deviceCapabilities: {
      hasVoiceRecognition: false,
      hasAccelerometer: false,
      hasGyroscope: false,
      hasGPS: false
    }
  },

  onInit() {
    this.loadSettings()
    this.checkDeviceCapabilities()
    this.getDeviceInfo()
  },

  onShow() {
    this.loadSettings()
  },

  loadSettings() {
    storage.get({
      key: 'settings',
      success: (data) => {
        if (data) {
          const savedSettings = JSON.parse(data.data || data)
          this.settings = { ...this.settings, ...savedSettings }
        }
      },
      fail: () => {
        // 使用默认设置
        this.saveSettings()
      }
    })
  },

  checkDeviceCapabilities() {
    // 检查设备功能
    this.checkVoiceRecognition()
    this.checkSensors()
  },

  checkVoiceRecognition() {
    try {
      voice.getSupportLanguages({
        success: (result) => {
          this.deviceCapabilities.hasVoiceRecognition = true
        },
        fail: () => {
          this.deviceCapabilities.hasVoiceRecognition = false
        }
      })
    } catch (error) {
      this.deviceCapabilities.hasVoiceRecognition = false
    }
  },

  checkSensors() {
    // 检查传感器
    try {
      sensor.getAccelerometer({
        success: () => {
          this.deviceCapabilities.hasAccelerometer = true
        },
        fail: () => {
          this.deviceCapabilities.hasAccelerometer = false
        }
      })

      sensor.getGyroscope({
        success: () => {
          this.deviceCapabilities.hasGyroscope = true
        },
        fail: () => {
          this.deviceCapabilities.hasGyroscope = false
        }
      })
    } catch (error) {
      console.info('Sensor check failed:', error)
    }
  },

  getDeviceInfo() {
    device.getInfo({
      success: (info) => {
        this.deviceInfo = info
      }
    })
  },

  saveSettings() {
    storage.set({
      key: 'settings',
      value: JSON.stringify(this.settings),
      success: () => {
        this.applySettings()
        prompt.showToast({
          message: '设置已保存',
          duration: 2000
        })
      },
      fail: () => {
        prompt.showToast({
          message: '保存设置失败',
          duration: 2000
        })
      }
    })
  },

  applySettings() {
    // 应用设置
    this.applyTheme()
    this.applyLanguage()
    this.applyVolume()
    this.applyDifficulty()
    this.applyAutoSave()
  },

  applyTheme() {
    // 应用主题设置
    const body = document.body
    body.className = body.className.replace(/theme-\w+/g, '')
    body.classList.add(`theme-${this.settings.theme}`)
  },

  applyLanguage() {
    // 应用语言设置
    // 这里可以实现多语言切换逻辑
  },

  applyVolume() {
    // 应用音量设置
    if (this.settings.backgroundMusic) {
      // 播放背景音乐
      this.playBackgroundMusic()
    } else {
      // 停止背景音乐
      this.stopBackgroundMusic()
    }
  },

  applyDifficulty() {
    // 应用难度设置
    if (this.settings.difficulty === 'adaptive') {
      this.enableAdaptiveDifficulty()
    }
  },

  applyAutoSave() {
    // 应用自动保存设置
    if (this.settings.autoSave) {
      this.enableAutoSave()
    } else {
      this.disableAutoSave()
    }
  },

  toggleSetting(settingName) {
    this.settings[settingName] = !this.settings[settingName]
    this.saveSettings()
  },

  updateSetting(settingName, value) {
    this.settings[settingName] = value
    this.saveSettings()
  },

  testVoiceRecognition() {
    if (this.isTestingVoice) return
    
    this.isTestingVoice = true
    this.voiceTestResult = '测试中...'
    
    voice.startListening({
      success: (result) => {
        this.voiceTestResult = `识别成功: "${result.text}"`
        this.isTestingVoice = false
      },
      fail: (error) => {
        this.voiceTestResult = `识别失败: ${error.message}`
        this.isTestingVoice = false
      }
    })
  },

  calibrateSensors() {
    // 校准传感器
    prompt.showDialog({
      title: '传感器校准',
      message: '请将设备放在水平面上，点击开始校准',
      buttons: [
        { text: '开始校准', color: '#1976d2' },
        { text: '取消', color: '#666666' }
      ],
      success: (result) => {
        if (result.index === 0) {
          this.startSensorCalibration()
        }
      }
    })
  },

  startSensorCalibration() {
    // 开始传感器校准
    try {
      sensor.calibrateAccelerometer({
        success: () => {
          prompt.showToast({
            message: '传感器校准成功',
            duration: 2000
          })
        },
        fail: () => {
          prompt.showToast({
            message: '传感器校准失败',
            duration: 2000
          })
        }
      })
    } catch (error) {
      prompt.showToast({
        message: '设备不支持传感器校准',
        duration: 2000
      })
    }
  },

  pairDevice() {
    // 设备配对
    if (this.settings.multiDeviceSync) {
      this.startDeviceDiscovery()
    } else {
      prompt.showToast({
        message: '多设备同步已关闭',
        duration: 2000
      })
    }
  },

  startDeviceDiscovery() {
    // 开始设备发现
    prompt.showDialog({
      title: '设备配对',
      message: '正在搜索附近的设备...',
      buttons: [
        { text: '停止搜索', color: '#f44336' }
      ]
    })
    
    // 模拟设备发现过程
    setTimeout(() => {
      this.showDiscoveredDevices()
    }, 3000)
  },

  showDiscoveredDevices() {
    // 显示发现的设备
    const devices = [
      { name: '华为平板', type: 'tablet', id: 'device1' },
      { name: '华为手机', type: 'phone', id: 'device2' }
    ]
    
    let deviceList = devices.map(device => `${device.name} (${device.type})`).join('\n')
    
    prompt.showDialog({
      title: '发现的设备',
      message: deviceList,
      buttons: [
        { text: '配对', color: '#4caf50' },
        { text: '取消', color: '#666666' }
      ],
      success: (result) => {
        if (result.index === 0) {
          this.pairWithDevice(devices[0])
        }
      }
    })
  },

  pairWithDevice(device) {
    // 与设备配对
    prompt.showToast({
      message: `正在与${device.name}配对...`,
      duration: 2000
    })
    
    setTimeout(() => {
      prompt.showToast({
        message: `配对成功！`,
        duration: 2000
      })
    }, 2000)
  },

  resetSettings() {
    // 重置设置为默认值
    prompt.showDialog({
      title: '重置设置',
      message: '确定要重置所有设置为默认值吗？',
      buttons: [
        { text: '确定', color: '#f44336' },
        { text: '取消', color: '#666666' }
      ],
      success: (result) => {
        if (result.index === 0) {
          this.settings = {
            voiceRecognition: true,
            sceneAwareness: true,
            multiDeviceSync: false,
            soundEffects: true,
            backgroundMusic: true,
            musicVolume: 50,
            effectVolume: 70,
            language: 'zh-CN',
            theme: 'dark',
            fontSize: 'medium',
            difficulty: 'adaptive',
            autoSave: true,
            saveInterval: 300,
            notifications: true,
            vibration: true
          }
          this.saveSettings()
        }
      }
    })
  },

  exportSettings() {
    // 导出设置
    const exportData = {
      settings: this.settings,
      exportTime: new Date().toISOString(),
      deviceInfo: this.deviceInfo
    }
    
    storage.set({
      key: 'settingsExport_' + Date.now(),
      value: JSON.stringify(exportData)
    })
    
    prompt.showToast({
      message: '设置已导出',
      duration: 2000
    })
  },

  importSettings() {
    // 导入设置
    // 这里可以实现从文件或云端导入设置的逻辑
    prompt.showToast({
      message: '导入功能开发中...',
      duration: 2000
    })
  },

  playBackgroundMusic() {
    // 播放背景音乐
    console.info('Playing background music')
  },

  stopBackgroundMusic() {
    // 停止背景音乐
    console.info('Stopping background music')
  },

  enableAdaptiveDifficulty() {
    // 启用自适应难度
    console.info('Enabling adaptive difficulty')
  },

  enableAutoSave() {
    // 启用自动保存
    console.info('Enabling auto save')
  },

  disableAutoSave() {
    // 禁用自动保存
    console.info('Disabling auto save')
  },

  showAbout() {
    // 显示关于信息
    router.push({
      uri: 'pages/about/about'
    })
  },

  showHelp() {
    // 显示帮助信息
    router.push({
      uri: 'pages/help/help'
    })
  },

  checkForUpdates() {
    // 检查更新
    prompt.showDialog({
      title: '检查更新',
      message: '正在检查新版本...',
      buttons: [
        { text: '确定', color: '#1976d2' }
      ]
    })
    
    setTimeout(() => {
      prompt.showToast({
        message: '当前已是最新版本',
        duration: 2000
      })
    }, 2000)
  }
}